import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import RootStore from 'store/RootStore';

import Loader from 'components/Loader';
import { classnames } from 'utils';

import classes from './PageLoader.module.scss';

const cnPageLoader = classnames(classes, 'pageLoader');

export type PageLoaderProps = {
    showLoading?: boolean;
    zIndex?: number;
};

export const PageLoader: React.FC<PageLoaderProps> = observer(({ showLoading, zIndex }) => {
    const isLoading = RootStore.pageLoader.loading;

    const [isShow, setIsShow] = useState(true);

    useEffect(() => {
        setIsShow(true);

        const setTimeoutId = setTimeout(() => {
            setIsShow(false);
        }, 1012);

        return () => {
            clearTimeout(setTimeoutId);
        };
    }, [isLoading, showLoading]);

    if (isShow || isLoading || showLoading) {
        return (
            <div className={cnPageLoader()} style={{ zIndex }} onScroll={(event) => event.stopPropagation()}>
                <Loader size="m" className={cnPageLoader('loader')} />
            </div>
        );
    }
    return null;
});
